package be.android.forap.dataprovider;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class ContactsIntegrityDb {

	// Database fields
	private SQLiteDatabase database;
	private MySQLiteHelper dbHelper;
	private String[] allColumns = {
			MySQLiteHelper.COLUMN_ID, 
			MySQLiteHelper.COLUMN_GLOBALCONTACT_ID,
			MySQLiteHelper.COLUMN_CONTACT_DIGEST};

	public ContactsIntegrityDb(Context context) {
		dbHelper = new MySQLiteHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}


	// Adding new contact
	public ContactIntegrityElement createContactIntegrity(String globalId, byte[] digest) {
		ContentValues values = new ContentValues();
		values.put(MySQLiteHelper.COLUMN_GLOBALCONTACT_ID, globalId);
		values.put(MySQLiteHelper.COLUMN_CONTACT_DIGEST, digest);
		long insertId = database.insert(MySQLiteHelper.TABLE_CONTACTS, null,values);
		// To show how to query
		Cursor cursor = database.query(MySQLiteHelper.TABLE_CONTACTS,allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null, null, null, null);
		cursor.moveToFirst();
		return cursorToContactIntegrityElement(cursor);
	}

	// Deleting single contact
	public void deleteContactIntegrity(String id) {
		database.delete(MySQLiteHelper.TABLE_CONTACTS, MySQLiteHelper.COLUMN_GLOBALCONTACT_ID	+ " = " + 
							DatabaseUtils.sqlEscapeString(id), null);
	}
	

	// Getting single contact
	public ContactIntegrityElement getContactIntegrity(String globalId) throws SQLException{
		Log.i("ID", " "+globalId);
		Cursor cursor = database.query(MySQLiteHelper.TABLE_CONTACTS, allColumns, MySQLiteHelper.COLUMN_GLOBALCONTACT_ID + "="
							+ DatabaseUtils.sqlEscapeString(globalId), null, null, null, null, null);
		boolean b = cursor.moveToFirst();
		if(b == false){
			Log.i("Cursor", "Cursor is false");
			throw new SQLException("No such entry");
		}
		Log.i("ID from cursor", " "+cursor.getString(1));
		return  cursorToContactIntegrityElement(cursor);
	}

	// Getting All Contact
	/*public List<ContactIntegrityElement> getAllContactsIntegrity() {
		List<Contact> contacts = new ArrayList<Contact>();
		Cursor cursor = database.query(MySQLiteHelper.TABLE_CONTACTS,allColumns, null, null, null, null, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Contact c = cursorToContact(cursor);
			contacts.add(c);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return contacts;
	}*/

	// Updating single contact
	public int updateContactIntegrity(String globalId, byte[] digest) {
		ContentValues values = new ContentValues();
        values.put(MySQLiteHelper.COLUMN_GLOBALCONTACT_ID,globalId);
        values.put(MySQLiteHelper.COLUMN_CONTACT_DIGEST, digest);

        // updating row
        return database.update(MySQLiteHelper.TABLE_CONTACTS, values, MySQLiteHelper.COLUMN_GLOBALCONTACT_ID + " = ?",
        		new String[]{DatabaseUtils.sqlEscapeString(globalId) });
	}   

	// Getting contacts Count
	public int getContactsCount() {
		String countQuery = "SELECT  * FROM " + MySQLiteHelper.TABLE_CONTACTS;
		Cursor cursor = database.rawQuery(countQuery, null);
		cursor.close();
		return cursor.getCount();
	}

	private ContactIntegrityElement cursorToContactIntegrityElement(Cursor cursor) {
		Log.i("Cursor",cursor.toString());
		ContactIntegrityElement cie = new ContactIntegrityElement(cursor.getLong(0),cursor.getString(1),cursor.getBlob(2));
		return cie;
	}

	private class MySQLiteHelper extends SQLiteOpenHelper {

		public static final String TABLE_CONTACTS = "Contacts";
		public static final String COLUMN_ID = "_id";
		public static final String COLUMN_GLOBALCONTACT_ID = "global_id";
		public static final String COLUMN_CONTACT_DIGEST = "digest";

		private static final String DATABASE_NAME = "forap.db";
		private static final int DATABASE_VERSION = 1;

		// Database creation sql statement
		private static final String DATABASE_CREATE = "create table "
				+ TABLE_CONTACTS + "( " 
				+ COLUMN_ID	+ " integer primary key not null, " 
				+ COLUMN_GLOBALCONTACT_ID + " text not null, "
				+ COLUMN_CONTACT_DIGEST + " none);";

		public MySQLiteHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase database) {
			database.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(MySQLiteHelper.class.getName(),
					"Upgrading database from version " + oldVersion + " to "
							+ newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
			onCreate(db);
		}

	}
}